import 'dart:convert';

import 'package:bike_ride/common/util/account_manager.dart';
import 'package:bike_ride/common/util/google_directions_m.dart';
import 'package:bike_ride/common/util/permission_utils.dart';
import 'package:bike_ride/generated/l10n.dart';
import 'package:bike_ride/main/app.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:geolocator/geolocator.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:http/http.dart' as http;

class GoogleMapUtils {
  static const googleApiKey = 'AIzaSyBaraKRPbNBd0BuaILJT1DrAfwZjtn8Yuc';

  static Future<GoogleDirectionsM?> getDirections(
      LatLng start, LatLng end) async {
    String url =
        "https://maps.googleapis.com/maps/api/directions/json?origin=${start.latitude},${start.longitude}&destination=${end.latitude},${end.longitude}&key=$googleApiKey";

    http.Response response = await http.get(Uri.parse(url));
    // 解析响应...
    // 根据响应结果，在地图上绘制路线
    assert(() {
      debugPrint(" ${response.statusCode}");
      debugPrint(" ${response.body}");
      return true;
    }());

    if (response.statusCode == 200) {
      final request = jsonDecode(response.body) as Map<String, dynamic>;
      return GoogleDirectionsM.fromJson(request);
    } else {
      return null;
    }
  }

  static getCurrentPosition(Function(Position) onResult,{bool showLoading = true}) {
    if (navigatorKey.currentContext == null) {
      final position = _defaultPosition();
      onResult(position);
    }
    PermissionUtil.handleLocationPermission(
        navigatorKey.currentContext!, (success, _) async {
          if (success) {
            if(showLoading){
              EasyLoading.show(status: '${S.current.positioning}...');
            }
            // 获取当前位置 7s
            final position = await Geolocator.getCurrentPosition(timeLimit: const Duration(seconds: 7)).catchError((error){
              EasyLoading.dismiss();
              return _defaultPosition();
            });
            AccountManager.updateUserLocation(
                lat: position.latitude, lng: position.longitude);
            AccountManager.handleAreaCode(
                lat: position.latitude, lng: position.longitude);
            EasyLoading.dismiss();
            onResult(position);
          } else {
            final position = _defaultPosition();
            onResult(position);
          }
    });
  }

  static Position _defaultPosition() {
    return Position(
        longitude: AccountManager.userLongitude!,
        latitude: AccountManager.userLatitude!,
        timestamp: DateTime.now(),
        accuracy: 0,
        altitude: 0,
        altitudeAccuracy: 0,
        heading: 0,
        headingAccuracy: 0,
        speed: 0,
        speedAccuracy: 0
    );
  }
}
